package com.by.common.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class   MvcConfig implements WebMvcConfigurer {
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();//启用默认的servlet配置 处理静态资源
    }

    /**
     * 上传的解析器
     *
     * @return
     */

    public StandardServletMultipartResolver multipartResolver(){
        return new StandardServletMultipartResolver();
    }
    /**
     * 跨域处理
     * @param registry
     */
    /*@Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")//拦截所有以/api开头的请求
                .allowedOrigins("*")//允许所有域名访问
                .allowedMethods("get","post","put","delete","options")//允许的方法
                .allowedHeaders("*")
                .allowCredentials(false)
                .maxAge(3600);
    }*/
    @Bean
    public CorsFilter corsFilter(){
        CorsConfiguration config =new CorsConfiguration();
        config.setAllowCredentials(false);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        config.setMaxAge(3600L);
        UrlBasedCorsConfigurationSource source=new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",config);
        CorsFilter filter=new CorsFilter(source);
        return filter;

    }
}
